package com.danawa.watcher.security;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.stereotype.Component;

import com.danawa.watcher.model.Role;
import com.danawa.watcher.model.User;
import com.danawa.watcherApi.database.command.common.Operator;
import com.danawa.watcherApi.database.domain.Member;
import com.danawa.watcherApi.database.service.WatcherService;

@Component
public class CustomAuthenticationProvider implements AuthenticationProvider {
	
	@Autowired
	private WatcherService watcherService;
	
	@Override
    public Authentication authenticate(Authentication authentication) {
        
		/**
		 * 로그인 폼에서 입력한 아이디와 패스워드 
		 */
		String username = authentication.getName();
        String password = (String) authentication.getCredentials();
        
        /**
         * watcher api 회원 정보를 얻기위한 커맨드 객체 
         */
        Member memberCommand = new Member();
        memberCommand.setOperator(Operator.EQUAL, "email", username);
        
        /**
         * 변수 초기화 
         */
        List<Member> memberList = null;
		Member member = null;
       	User user = null;
       	
		try {
			/**
			 * 멤버 정보 가져오기 
			 */
       		memberList = (List<Member>) watcherService.getMembers(memberCommand);
			member = memberList.get(0);
			
			user = new User();
			user.setUsername(member.getEmail());
			user.setPassword(member.getPassword());
			user.setMemberSeq(member.getMemberSeq());
			user.setTrackingCount(member.getTrackingCount());
			
			/**
			 * 회원 권한 추가 
			 */
			Role r = new Role();
			r.setName("ROLE_USER");
			List<Role> roles = new ArrayList<Role>();
			roles.add(r);
			user.setAuthorities(roles);
			
		} catch (Throwable e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
        if (user == null) {
            throw new BadCredentialsException("이메일이 존재하지 않습니다.");
        }
        
        /**
         * 패스워드 비교 
         */
        if (!password.equals(user.getPassword())) {
            throw new BadCredentialsException("패스워드가 일치하지 않습니다.");
        }
        
        Collection<? extends GrantedAuthority> authorities = user.getAuthorities();
        return new UsernamePasswordAuthenticationToken(user, null, authorities);
    
	}
 
    @Override
    public boolean supports(Class<?> arg0) {
        return true;
    }
}
